<template>
  <div class="template-renderer">
    <!-- 网格背景 -->
    <div 
      v-if="mode === 'design' && gridConfig.enabled" 
      class="grid-background"
      :style="gridStyle"
    ></div>
    
    <!-- 对齐参考线 -->
    <div 
      v-if="mode === 'design' && alignmentGuides.visible" 
      class="alignment-guides"
    >
      <div
        v-for="x in alignmentGuides.vertical"
        :key="`v-${x}`"
        class="guide-line vertical"
        :style="{ left: x + 'px' }"
      ></div>
      <div
        v-for="y in alignmentGuides.horizontal"
        :key="`h-${y}`"
        class="guide-line horizontal"
        :style="{ top: y + 'px' }"
      ></div>
    </div>

    <!-- 设计模式下的组件容器 -->
    <div
      v-for="component in sortedComponents"
      :key="component.id"
      :class="[
        'template-component',
        component.type,
        {
          'selected': isSelected(component),
          'dragging': isDragging(component),
          'snapping': isSnapping(component),
          'calculation': component.content?.paramType === 'calculation'
        }
      ]"
      :style="getComponentStyle(component)"
      @click="handleComponentClick(component, $event)"
      @dblclick="handleComponentDoubleClick(component, $event)"
      @mousedown="startDrag(component, $event)"
    >
      <!-- 动态渲染组件 -->
      <component
        :is="getComponentRenderer(component.type)"
        :component="component"
        :config="config"
        :mode="mode"
        :test-data="testData"
        @update="handleComponentUpdate(component.id, $event)"
      />
      
      <!-- 设计模式下的操作手柄 -->
      <div v-if="mode === 'design'" class="component-controls">
        <!-- 拖拽手柄 -->
        <div class="control-handle drag-handle" @mousedown="startDrag(component, $event)">
          <i class="el-icon-rank"></i>
        </div>
        
        <!-- 调整大小手柄 -->
        <div 
          class="control-handle resize-handle" 
          @mousedown="startResize(component, $event)"
        >
          <i class="el-icon-full-screen"></i>
        </div>
        
        <!-- 删除按钮 -->
        <div 
          class="control-handle delete-handle" 
          @click="removeComponent(component.id)"
        >
          <i class="el-icon-close"></i>
        </div>
      </div>
      
      <!-- 组件标签（设计模式） -->
      <div v-if="mode === 'design'" class="component-label">
        <span class="label-text">{{ getComponentLabel(component) }}</span>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-if="sortedComponents.length === 0" class="empty-template">
      <i class="el-icon-document empty-icon"></i>
      <p class="empty-text">暂无组件，请从左侧组件库拖拽添加</p>
    </div>
  </div>
</template>

<script>
// 导入组件渲染器
import TextRenderer from './renderers/TextRenderer.vue'
import NumberRenderer from './renderers/NumberRenderer.vue'
import ParameterRenderer from './renderers/ParameterRenderer.vue'
import MultiMeasureRenderer from './renderers/MultiMeasureRenderer.vue'
import DynamicTableRenderer from './renderers/DynamicTableRenderer.vue'
import ImageRenderer from './renderers/ImageRenderer.vue'
import HeaderRenderer from './renderers/HeaderRenderer.vue'
import FooterRenderer from './renderers/FooterRenderer.vue'
import LayoutTableRenderer from './renderers/LayoutTableRenderer.vue'
export default {
  name: 'TemplateRenderer',
  components: {
     TextRenderer,
    NumberRenderer,
    ParameterRenderer,
    MultiMeasureRenderer,
    DynamicTableRenderer,
    ImageRenderer,
    HeaderRenderer,
    FooterRenderer,
    LayoutTableRenderer
  },
  props: {
    components: {
      type: Array,
      default: () => []
    },
    config: {
      type: Object,
      default: () => ({})
    },
    mode: {
      type: String,
      default: 'design' // design, preview, generate
    },
    testData: {
      type: Object,
      default: () => ({})
    },
    selectedComponentId: {
      type: String,
      default: null
    },
    draggingComponentId: {
      type: String,
      default: null
    },
    gridConfig: {
      type: Object,
      default: () => ({
        enabled: true,
        size: 20,
        snap: true,
        snapTolerance: 5,
        color: '#e0e0e0',
        showGuides: true
      })
    }
  },
  data() {
    return {
      // 拖拽状态
      dragState: {
        isDragging: false,
        startX: 0,
        startY: 0,
        originalX: 0,
        originalY: 0
      },
      
      // 调整大小状态
      resizeState: {
        isResizing: false,
        startX: 0,
        startY: 0,
        originalWidth: 0,
        originalHeight: 0
      },
      
      // 对齐参考线状态
      alignmentGuides: {
        vertical: [],
        horizontal: [],
        visible: false
      },
      
      // 吸附状态
      snapState: {
        snappingComponentId: null,
        snapType: null // 'grid', 'component', 'edge'
      }
    }
  },
  computed: {
    /**
     * 排序后的组件（按位置排序）
     */
    sortedComponents() {
      return [...this.components].sort((a, b) => {
        // 按 Y 坐标排序，然后按 X 坐标排序
        if (a.position.y !== b.position.y) {
          return a.position.y - b.position.y
        }
        return a.position.x - b.position.x
      })
    },
    
    /**
     * 网格样式
     */
    gridStyle() {
      return {
        backgroundSize: `${this.gridConfig.size}px ${this.gridConfig.size}px`,
        backgroundColor: 'transparent',
        backgroundImage: `
          linear-gradient(${this.gridConfig.color} 1px, transparent 1px),
          linear-gradient(90deg, ${this.gridConfig.color} 1px, transparent 1px)
        `
      }
    }
  },
  watch: {
    // 监听组件列表变化，确保实时渲染
    components: {
      handler(newVal) {
        console.log('渲染组件更新：', newVal)
      },
      deep: true,
      immediate: true
    },
    draggingComponentId: {
      handler(newVal) {
        if (newVal) {
          console.log('开始拖拽组件:', newVal)
        } else {
          console.log('结束拖拽组件')
        }
      },
      immediate: false
    }
  },
  mounted() {
    // 添加键盘事件监听
    document.addEventListener('keydown', this.handleKeyDown)
  },
  methods: {
    /**
     * 获取组件渲染器名称
     */
      getComponentRenderer(type) {
      const rendererMap = {
        text: 'TextRenderer',
        number: 'NumberRenderer',
        parameter: 'ParameterRenderer',
        multiMeasure: 'MultiMeasureRenderer',
        dynamicTable: 'DynamicTableRenderer',
        image: 'ImageRenderer',
        header: 'HeaderRenderer',
        footer: 'FooterRenderer',
        layoutTable: 'LayoutTableRenderer'
      }
      return rendererMap[type] || 'TextRenderer'
    },
    
    /**
     * 获取组件样式
     */
    getComponentStyle(component) {
      const baseStyle = {
        position: this.mode === 'design' ? 'absolute' : 'absolute',
        left: `${component.position.x}px`,
        top: `${component.position.y}px`,
        width: `${component.position.width}px`,
        height: `${component.position.height}px`,
        zIndex: component.zIndex || 1
      }

      // 合并自定义样式
      if (component.style) {
        Object.assign(baseStyle, component.style)
      }

      // 生成模式样式调整
      if (this.mode === 'generate') {
        baseStyle.marginBottom = '10px'
      }

      return baseStyle
    },
    
    /**
     * 获取组件标签
     */
    getComponentLabel(component) {
      const labelMap = {
        text: '文本',
        table: '表格',
        parameter: '参数',
        image: '图片',
        header: '页眉',
        footer: '页脚'
      }
      
      let label = labelMap[component.type] || component.type
      
      // 添加具体内容标识
      if (component.type === 'text' && component.content?.text) {
        label += `: ${component.content.text.substring(0, 10)}...`
      } else if (component.type === 'parameter' && component.content?.paramCode) {
        label += `: ${component.content.paramCode}`
      }
      
      return label
    },
    
    /**
     * 检查组件是否被选中
     */
    isSelected(component) {
      return this.mode === 'design' && this.selectedComponentId === component.id
    },
    
    /**
     * 检查组件是否正在拖拽
     */
    isDragging(component) {
      return this.mode === 'design' && this.draggingComponentId === component.id
    },
    
    /**
     * 检查组件是否正在吸附
     */
    isSnapping(component) {
      return this.mode === 'design' && this.snapState.snappingComponentId === component.id
    },
    
    /**
     * 处理组件点击
     */
    handleComponentClick(component, event) {
      event.stopPropagation()
      
      if (this.mode === 'design') {
        this.$emit('select-component', component)
      }
    },
    
    /**
     * 开始拖拽
     */
    startDrag(component, event) {
      if (this.mode !== 'design') return
      
      event.stopPropagation()
      event.preventDefault()
      
      this.dragState = {
        isDragging: true,
        startX: event.clientX,
        startY: event.clientY,
        originalX: component.position.x,
        originalY: component.position.y,
        currentComponent: component
      }
      
      this.$emit('drag-start', component)
      
      // 添加全局事件监听
      document.addEventListener('mousemove', this.handleDragMove)
      document.addEventListener('mouseup', this.handleDragEnd)
    },

    /**
     * 处理拖拽移动
     */
    handleDragMove(event) {
      if (!this.dragState.isDragging || !this.dragState.currentComponent) return
      
      const deltaX = event.clientX - this.dragState.startX
      const deltaY = event.clientY - this.dragState.startY
      
      let newX = Math.max(0, this.dragState.originalX + deltaX)
      let newY = Math.max(0, this.dragState.originalY + deltaY)

      // 应用吸附逻辑
      const snappedPosition = this.calculateSnapPosition(
        this.dragState.currentComponent,
        newX,
        newY,
        this.dragState.currentComponent.position.width,
        this.dragState.currentComponent.position.height
      )

      // 更新吸附状态
      if (snappedPosition.snapped) {
        this.snapState.snappingComponentId = this.dragState.currentComponent.id
        this.snapState.snapType = snappedPosition.snapType
      }

      this.$emit('component-move', {
        componentId: this.dragState.currentComponent.id,
        x: snappedPosition.x,
        y: snappedPosition.y
      })
    },
    
    /**
     * 处理拖拽结束
     */
    handleDragEnd() {
      if (!this.dragState.isDragging) return
      
      this.dragState.isDragging = false
      this.clearAlignmentGuides()
      this.clearSnapState()
      this.$emit('drag-end')
      
      // 移除全局事件监听
      document.removeEventListener('mousemove', this.handleDragMove)
      document.removeEventListener('mouseup', this.handleDragEnd)
    },
    
    /**
     * 开始调整大小
     */
    startResize(component, event) {
      if (this.mode !== 'design') return
      
      event.stopPropagation()
      event.preventDefault()
      
      this.resizeState = {
        isResizing: true,
        startX: event.clientX,
        startY: event.clientY,
        originalWidth: component.position.width,
        originalHeight: component.position.height,
        currentComponent: component
      }
      
      this.$emit('resize-start', component)
      
      // 添加全局事件监听
      document.addEventListener('mousemove', this.handleResizeMove)
      document.addEventListener('mouseup', this.handleResizeEnd)
    },
    
    /**
     * 处理调整大小移动
     */
    handleResizeMove(event) {
      if (!this.resizeState.isResizing || !this.resizeState.currentComponent) return
      
      const deltaX = event.clientX - this.resizeState.startX
      const deltaY = event.clientY - this.resizeState.startY
      
      const minWidth = 50
      const minHeight = 30
      
      let newWidth = Math.max(minWidth, this.resizeState.originalWidth + deltaX)
      let newHeight = Math.max(minHeight, this.resizeState.originalHeight + deltaY)

      // 应用吸附逻辑
      const snappedPosition = this.calculateSnapPosition(
        this.resizeState.currentComponent,
        this.resizeState.currentComponent.position.x,
        this.resizeState.currentComponent.position.y,
        newWidth,
        newHeight
      )

      // 更新吸附状态
      if (snappedPosition.snapped) {
        this.snapState.snappingComponentId = this.resizeState.currentComponent.id
        this.snapState.snapType = snappedPosition.snapType
      }

      this.$emit('component-resize', {
        componentId: this.resizeState.currentComponent.id,
        width: snappedPosition.width,
        height: snappedPosition.height
      })
    },
    
    /**
     * 处理调整大小结束
     */
    handleResizeEnd() {
      if (!this.resizeState.isResizing) return
      
      this.resizeState.isResizing = false
      this.clearAlignmentGuides()
      this.clearSnapState()
      this.$emit('resize-end')
      
      // 移除全局事件监听
      document.removeEventListener('mousemove', this.handleResizeMove)
      document.removeEventListener('mouseup', this.handleResizeEnd)
    },
    
    /**
     * 计算吸附后的位置
     */
    calculateSnapPosition(component, newX, newY, newWidth, newHeight) {
      if (!this.gridConfig.snap) {
        return { 
          x: newX, 
          y: newY, 
          width: newWidth, 
          height: newHeight,
          snapped: false,
          snapType: null
        }
      }

      let snappedX = newX
      let snappedY = newY
      let snappedWidth = newWidth
      let snappedHeight = newHeight
      let snapped = false
      let snapType = null
      
      const guides = {
        vertical: [],
        horizontal: []
      }

      // 1. 栅格吸附
      if (this.gridConfig.enabled) {
        const gridSnap = this.snapToGrid(newX, newY, newWidth, newHeight)
        if (gridSnap.snappedX || gridSnap.snappedY) {
          snapped = true
          snapType = 'grid'
        }
        snappedX = gridSnap.x
        snappedY = gridSnap.y
        snappedWidth = gridSnap.width
        snappedHeight = gridSnap.height
        
        if (gridSnap.snappedX) guides.vertical.push(newX)
        if (gridSnap.snappedY) guides.horizontal.push(newY)
      }

      // 2. 组件边界吸附
      const componentSnap = this.snapToComponents(component, snappedX, snappedY, snappedWidth, snappedHeight)
      if (componentSnap.snapped) {
        snapped = true
        snapType = 'component'
      }
      snappedX = componentSnap.x
      snappedY = componentSnap.y
      snappedWidth = componentSnap.width
      snappedHeight = componentSnap.height
      
      guides.vertical.push(...componentSnap.guides.vertical)
      guides.horizontal.push(...componentSnap.guides.horizontal)

      // 3. 画布边界吸附
      const edgeSnap = this.snapToEdges(snappedX, snappedY, snappedWidth, snappedHeight)
      if (edgeSnap.snapped) {
        snapped = true
        snapType = 'edge'
      }
      snappedX = edgeSnap.x
      snappedY = edgeSnap.y
      
      guides.vertical.push(...edgeSnap.guides.vertical)
      guides.horizontal.push(...edgeSnap.guides.horizontal)

      // 更新对齐参考线
      this.updateAlignmentGuides(guides)

      return {
        x: snappedX,
        y: snappedY,
        width: snappedWidth,
        height: snappedHeight,
        snapped,
        snapType
      }
    },

    /**
     * 栅格吸附
     */
    snapToGrid(x, y, width, height) {
      const gridSize = this.gridConfig.size
      const tolerance = this.gridConfig.snapTolerance
      
      let snappedX = x
      let snappedY = y
      let snappedWidth = width
      let snappedHeight = height
      let snappedXFlag = false
      let snappedYFlag = false

      // X坐标吸附
      const xRemainder = x % gridSize
      if (Math.abs(xRemainder) <= tolerance) {
        snappedX = x - xRemainder
        snappedXFlag = true
      } else if (Math.abs(xRemainder - gridSize) <= tolerance) {
        snappedX = x + (gridSize - xRemainder)
        snappedXFlag = true
      }

      // Y坐标吸附
      const yRemainder = y % gridSize
      if (Math.abs(yRemainder) <= tolerance) {
        snappedY = y - yRemainder
        snappedYFlag = true
      } else if (Math.abs(yRemainder - gridSize) <= tolerance) {
        snappedY = y + (gridSize - yRemainder)
        snappedYFlag = true
      }

      // 宽度吸附
      const widthRemainder = width % gridSize
      if (Math.abs(widthRemainder) <= tolerance) {
        snappedWidth = width - widthRemainder
      } else if (Math.abs(widthRemainder - gridSize) <= tolerance) {
        snappedWidth = width + (gridSize - widthRemainder)
      }

      // 高度吸附
      const heightRemainder = height % gridSize
      if (Math.abs(heightRemainder) <= tolerance) {
        snappedHeight = height - heightRemainder
      } else if (Math.abs(heightRemainder - gridSize) <= tolerance) {
        snappedHeight = height + (gridSize - heightRemainder)
      }

      return {
        x: snappedX,
        y: snappedY,
        width: snappedWidth,
        height: snappedHeight,
        snappedX: snappedXFlag,
        snappedY: snappedYFlag
      }
    },

    /**
     * 组件边界吸附
     */
    snapToComponents(currentComponent, x, y, width, height) {
      const tolerance = this.gridConfig.snapTolerance
      const guides = {
        vertical: [],
        horizontal: []
      }

      let snappedX = x
      let snappedY = y
      let snappedWidth = width
      let snappedHeight = height
      let snapped = false

      // 当前组件的边界
      const currentBounds = {
        left: x,
        right: x + width,
        top: y,
        bottom: y + height,
        centerX: x + width / 2,
        centerY: y + height / 2
      }

      // 检查其他组件
      this.components.forEach(component => {
        if (component.id === currentComponent.id) return

        const bounds = {
          left: component.position.x,
          right: component.position.x + component.position.width,
          top: component.position.y,
          bottom: component.position.y + component.position.height,
          centerX: component.position.x + component.position.width / 2,
          centerY: component.position.y + component.position.height / 2
        }

        // 水平对齐检查
        const horizontalSnapped = this.checkHorizontalAlignment(currentBounds, bounds, tolerance, guides, (delta) => {
          snappedX += delta
          snapped = true
        })
        console.log('水平对齐检查', horizontalSnapped)

        // 垂直对齐检查
        const verticalSnapped = this.checkVerticalAlignment(currentBounds, bounds, tolerance, guides, (delta) => {
          snappedY += delta
          snapped = true
        })
        console.log('垂直对齐检查', verticalSnapped)

      })

      return {
        x: snappedX,
        y: snappedY,
        width: snappedWidth,
        height: snappedHeight,
        guides,
        snapped
      }
    },

    /**
     * 检查水平对齐
     */
    checkHorizontalAlignment(current, target, tolerance, guides, onSnap) {
      let snapped = false

      // 左边界对齐
      if (Math.abs(current.left - target.left) <= tolerance) {
        onSnap(target.left - current.left)
        guides.vertical.push(target.left)
        snapped = true
      }
      // 右边界对齐
      if (Math.abs(current.right - target.right) <= tolerance) {
        onSnap(target.right - current.right)
        guides.vertical.push(target.right)
        snapped = true
      }
      // 中心对齐
      if (Math.abs(current.centerX - target.centerX) <= tolerance) {
        onSnap(target.centerX - current.centerX)
        guides.vertical.push(target.centerX)
        snapped = true
      }
      // 左对右
      if (Math.abs(current.left - target.right) <= tolerance) {
        onSnap(target.right - current.left)
        guides.vertical.push(target.right)
        snapped = true
      }
      // 右对左
      if (Math.abs(current.right - target.left) <= tolerance) {
        onSnap(target.left - current.right)
        guides.vertical.push(target.left)
        snapped = true
      }

      return snapped
    },

    /**
     * 检查垂直对齐
     */
    checkVerticalAlignment(current, target, tolerance, guides, onSnap) {
      let snapped = false

      // 上边界对齐
      if (Math.abs(current.top - target.top) <= tolerance) {
        onSnap(target.top - current.top)
        guides.horizontal.push(target.top)
        snapped = true
      }
      // 下边界对齐
      if (Math.abs(current.bottom - target.bottom) <= tolerance) {
        onSnap(target.bottom - current.bottom)
        guides.horizontal.push(target.bottom)
        snapped = true
      }
      // 中心对齐
      if (Math.abs(current.centerY - target.centerY) <= tolerance) {
        onSnap(target.centerY - current.centerY)
        guides.horizontal.push(target.centerY)
        snapped = true
      }
      // 上对下
      if (Math.abs(current.top - target.bottom) <= tolerance) {
        onSnap(target.bottom - current.top)
        guides.horizontal.push(target.bottom)
        snapped = true
      }
      // 下对上
      if (Math.abs(current.bottom - target.top) <= tolerance) {
        onSnap(target.top - current.bottom)
        guides.horizontal.push(target.top)
        snapped = true
      }

      return snapped
    },

    /**
     * 画布边界吸附
     */
    snapToEdges(x, y, width, height) {
      const tolerance = this.gridConfig.snapTolerance
      const canvas = this.$el.getBoundingClientRect()
      const guides = {
        vertical: [],
        horizontal: []
      }

      let snappedX = x
      let snappedY = y
      let snapped = false

      // 左边界吸附
      if (x <= tolerance) {
        snappedX = 0
        guides.vertical.push(0)
        snapped = true
      }

      // 上边界吸附
      if (y <= tolerance) {
        snappedY = 0
        guides.horizontal.push(0)
        snapped = true
      }

      // 右边界吸附
      const rightEdge = canvas.width - width
      if (Math.abs(x - rightEdge) <= tolerance) {
        snappedX = rightEdge
        guides.vertical.push(canvas.width)
        snapped = true
      }

      // 下边界吸附（考虑实际内容区域）
      const bottomEdge = canvas.height - height
      if (Math.abs(y - bottomEdge) <= tolerance) {
        snappedY = bottomEdge
        guides.horizontal.push(canvas.height)
        snapped = true
      }

      return {
        x: snappedX,
        y: snappedY,
        guides,
        snapped
      }
    },

    /**
     * 更新对齐参考线
     */
    updateAlignmentGuides(guides) {
      this.alignmentGuides = {
        vertical: [...new Set(guides.vertical)], // 去重
        horizontal: [...new Set(guides.horizontal)],
        visible: guides.vertical.length > 0 || guides.horizontal.length > 0
      }
    },

    /**
     * 清除对齐参考线
     */
    clearAlignmentGuides() {
      this.alignmentGuides = {
        vertical: [],
        horizontal: [],
        visible: false
      }
    },

    /**
     * 清除吸附状态
     */
    clearSnapState() {
      this.snapState = {
        snappingComponentId: null,
        snapType: null
      }
    },
    
    /**
     * 处理组件更新
     */
    handleComponentUpdate(componentId, updates) {
      this.$emit('update-component', componentId, updates)
    },
    
    /**
     * 移除组件
     */
    removeComponent(componentId) {
      this.$emit('component-remove', componentId)
    },
    
    /**
     * 处理组件双击
     */
    handleComponentDoubleClick(component, event) {
      event.stopPropagation()
      
      if (this.mode === 'design') {
        this.$emit('component-double-click', component)
      }
    },
    
    /**
     * 处理键盘事件
     */
    handleKeyDown(event) {
      if (this.mode !== 'design' || !this.selectedComponentId) return
      
      const selectedComponent = this.components.find(comp => comp.id === this.selectedComponentId)
      if (!selectedComponent) return
      
      const moveStep = event.shiftKey ? 10 : 1 // Shift键加速移动
      
      switch (event.key) {
        case 'ArrowUp':
          event.preventDefault()
          this.$emit('component-move', {
            componentId: selectedComponent.id,
            x: selectedComponent.position.x,
            y: Math.max(0, selectedComponent.position.y - moveStep)
          })
          break
        case 'ArrowDown':
          event.preventDefault()
          this.$emit('component-move', {
            componentId: selectedComponent.id,
            x: selectedComponent.position.x,
            y: selectedComponent.position.y + moveStep
          })
          break
        case 'ArrowLeft':
          event.preventDefault()
          this.$emit('component-move', {
            componentId: selectedComponent.id,
            x: Math.max(0, selectedComponent.position.x - moveStep),
            y: selectedComponent.position.y
          })
          break
        case 'ArrowRight':
          event.preventDefault()
          this.$emit('component-move', {
            componentId: selectedComponent.id,
            x: selectedComponent.position.x + moveStep,
            y: selectedComponent.position.y
          })
          break
        case 'Delete':
          event.preventDefault()
          this.$emit('component-remove', selectedComponent.id)
          break
      }
    }
  },
  
  beforeDestroy() {
    // 清理事件监听
    document.removeEventListener('mousemove', this.handleDragMove)
    document.removeEventListener('mouseup', this.handleDragEnd)
    document.removeEventListener('mousemove', this.handleResizeMove)
    document.removeEventListener('mouseup', this.handleResizeEnd)
    document.removeEventListener('keydown', this.handleKeyDown)
  }
}
</script>

<style scoped>
.template-renderer {
  position: relative;
  width: 100%;
  min-height: 100%;
  background: white;
}

/* 网格背景 */
.grid-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 0;
}

/* 对齐参考线 */
.alignment-guides {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 999;
}

.guide-line {
  position: absolute;
  background: #ff4444;
  z-index: 1000;
}

.guide-line.vertical {
  width: 1px;
  height: 100%;
  top: 0;
}

.guide-line.horizontal {
  height: 1px;
  width: 100%;
  left: 0;
}

/* 组件基础样式 */
.template-component {
  position: absolute;
  border: 1px dashed transparent;
  transition: all 0.2s ease;
  cursor: pointer;
  box-sizing: border-box;
}

.template-component:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.template-component.selected {
  border: 2px solid #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
  z-index: 100;
}

.template-component.dragging {
  opacity: 0.8;
  border: 2px solid #409eff;
  box-shadow: 0 4px 20px rgba(64, 158, 255, 0.3);
  cursor: grabbing;
  z-index: 1000;
  transform: rotate(2deg);
  transition: transform 0.1s ease;
}

/* 吸附时的组件样式 */
.template-component.snapping {
  border: 2px dashed #67c23a !important;
  box-shadow: 0 0 10px rgba(103, 194, 58, 0.5) !important;
}

.template-component.calculation {
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
}

/* 组件控制手柄 */
.component-controls {
  position: absolute;
  top: -24px;
  right: 0;
  display: flex;
  gap: 2px;
  opacity: 0;
  transition: opacity 0.2s;
}

.template-component.selected .component-controls {
  opacity: 1;
}

.control-handle {
  width: 20px;
  height: 20px;
  background: #409eff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 10px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.control-handle:hover {
  background: #66b1ff;
  transform: scale(1.1);
}

.drag-handle {
  cursor: move;
}

.resize-handle {
  cursor: nwse-resize;
}

.delete-handle {
  background: #f56c6c;
}

.delete-handle:hover {
  background: #f78989;
}

/* 组件标签 */
.component-label {
  position: absolute;
  top: -20px;
  left: 0;
  background: #409eff;
  color: white;
  padding: 2px 6px;
  border-radius: 2px;
  font-size: 10px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.2s;
}

.template-component.selected .component-label {
  opacity: 1;
}

.label-text {
  font-weight: 500;
}

/* 空状态 */
.empty-template {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #c0c4cc;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 14px;
  margin: 0;
}

/* 生成模式样式 */
.template-renderer.generate-mode .template-component {
  position: absolute !important;
  page-break-inside: avoid;
  border: none !important;
  box-shadow: none !important;
  margin-bottom: 0;
}

.template-renderer.generate-mode .component-controls,
.template-renderer.generate-mode .component-label {
  display: none;
}

/* 预览模式样式 */
.template-renderer.preview-mode .template-component {
  border: 1px solid transparent;
}

.template-renderer.preview-mode .template-component:hover {
  border-color: #e6e8eb;
}

.template-renderer.preview-mode .component-controls,
.template-renderer.preview-mode .component-label {
  display: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .component-controls {
    flex-direction: column;
    top: -60px;
    right: 0;
  }
  
  .component-label {
    font-size: 8px;
    max-width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

/* 打印样式 */
@media print {
  .template-component {
    position: relative !important;
    page-break-inside: avoid;
    border: none !important;
    box-shadow: none !important;
  }
  
  .component-controls,
  .component-label {
    display: none !important;
  }
}
</style>